package com.cqc.listpopupmenu01;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private MyAdapter adapter;
    private List<String> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            list.add("item" + i);
        }

        listView = (ListView) findViewById(R.id.listView);
        adapter = new MyAdapter(list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = (String) parent.getItemAtPosition(position);
                Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
            }
        });

        adapter.setOnDeleteClickListener(new MyAdapter.OnDeleteClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                onClick(view, position);
            }
        });
    }

    private void onClick(final View view, final int position) {
        view.post(new Runnable() {
            @Override
            public void run() {
                showPopuMenu(view, position);
            }
        });
    }

    private void showPopuMenu(final View v, final int position) {
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
        popupMenu.getMenuInflater().inflate(R.menu.popup, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_remove:
                        list.remove(position);
                        adapter.notifyDataSetChanged();
                        return true;
                }
                return false;
            }
        });
        popupMenu.show();
    }


}
